package com.weijian.config.web;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

/**
 * Controller层日志切面
 * 统一处理Controller层的异常日志记录
 */
@Aspect
@Component
@Slf4j
public class ControllerLogAspect {

    /**
     * 定义切入点：拦截controller包下所有类的所有方法
     */
    @Pointcut("execution(public * com.weijian.controller..*.*(..))")
    public void controllerLog() {
    }

    /**
     * 异常通知：在方法抛出异常后执行
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(pointcut = "controllerLog()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        // 获取请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();

            // 记录异常日志
            log.error("=====================开始记录======================");
            log.error("异常拦截开始");
            log.error("请求URL: {}", request.getRequestURL().toString());
            log.error("请求方法: {}", request.getMethod());
            log.error("请求类方法: {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
            log.error("请求参数: {}", Arrays.toString(joinPoint.getArgs()));
            log.error("异常信息: {}", e.getMessage());
            log.error("异常堆栈: ", e);
            log.error("异常拦截结束");
            log.error("======================结束记录=====================");
        }
    }
}
